import WxRequest from 'mina-request'
import {
  env
} from './env'
import '@/utils/extendApi'
import {
  toast
} from '@/utils/extendApi'
import {
  clearStorage,
  getStorage
} from '@/utils/storage'
import userStore from '@/store/userStore'
// 对 WxRequest 进行实例化
const instance = new WxRequest({
  baseURL: env.baseURL, // 使用时请换成真实接口
  timeout: 150000, // 超时时长
  isLoading: false // 是否使用默认的 loading 效果
})

// 添加请求拦截器
instance.interceptors.request = (config) => {
  const token = getStorage('user.token')
  if (token) {
    config.header['authorization'] = token
  }
  return config
}

// 添加响应拦截器
instance.interceptors.response = (response) => {
  if (response.isSuccess) {
    if (response.data.code === 200) {
      return Promise.resolve(response.data)
    }
    toast({
      title: response.data.message,
      draution: 2000
    })
    if (response.data.code === 401) {
      clearStorage()
      userStore.setToken('')
      userStore.setUserInfo('')
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/to-login/to-login?message=请先登录~',
        })
      }, 1000)
      return Promise.reject(response.data.message)
    }
    if (response.data.code === 402) {
      clearStorage()
      userStore.setToken('')
      userStore.setUserInfo('')
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/to-login/to-login?message=登录已过期，请重新登录~',
        })
      },1000)
      return Promise.reject(response.data.message)
    }
    return Promise.reject(response.data.message)
  } else {
    console.log(response)
    return Promise.reject('系统出错了~~~')
  }
}

export default instance